/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.util.List;
import javax.persistence.EntityManager;
import Bean.Lei;
import javax.annotation.Resource;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author alexandre
 */
@Stateless(name = "LeiDAO")
@TransactionManagement(TransactionManagementType.CONTAINER)
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class LeiDAO {
    
    @PersistenceContext(unitName = "PersistenceUnit")
    private EntityManager em;

    @Resource
    private SessionContext context;//Session context que monitora se algum erro ocorre para fazer rollback
    
    
    public void add(Lei lei){
       // EntityManager em = JPAUtil.getInstance().getEntityManager();
       try{
           em.persist(lei);
       }
       catch(Exception e){
           e.printStackTrace();
       }
        
    }
    
    
    public void del(Lei lei){
       // EntityManager em = JPAUtil.getInstance().getEntityManager();
        Lei lei2 = em.merge(lei);
        em.remove(lei2);
    }
    
    public void edit(Lei lei){
       // EntityManager em = JPAUtil.getInstance().getEntityManager();
        em.merge(lei);
    }
    public List<Lei> AllLeis(){
        //return JPAUtil.getInstance().getList(Lei.class, "SELECT lei FROM Lei lei");
         Query query = em.createQuery("select lei from Lei lei");
        List<Lei> lei =  query.getResultList();
        return lei;
    }
    
    public Lei LeiID(int id){
        //return JPAUtil.getInstance().getEntity(Lei.class, id);
        Query query = em.createQuery("select lei from Lei lei where lei.id=:id");
        query.setParameter("id", id);
        Lei lei =(Lei) query.getSingleResult();
        return lei;
    }
    
    public Lei getLeiPorEscola(int id){
       // return JPAUtil.getInstance().getLeiPorEscola(Lei.class, "select lei from Lei lei where lei.escola.id=:id", id);
        Query query = em.createQuery("select lei from Lei lei where lei.escola.id=:id");
        query.setParameter("id", id);
        Lei lei =(Lei)query.getSingleResult();
        return lei;
    }
    
     public List<Lei> getLeiPorProfessor(int id){
        //return JPAUtil.getInstance().getLeiPorEscola(Lei.class, "select lei from Lei lei where lei.prof.id=:id", id);
         Query query = em.createQuery("select lei from Lei lei where lei.prof.id=:id");
         query.setParameter("id", id);
         List<Lei> lei = query.getResultList();
         return lei;
    }
    
}
